/**
 * 会员模块
 * @author jhua.zuo<jhua.zuo@baisonmail.com>
 * @date 2015-10-28
 */
angular.module('baisonMember', ['baisonDb', 'baisonService'])
        //会员模型
        .factory('VIP', ['$q', '$rootScope', 'apiService', 'dbSelect', 'dbReplace', 'timeStamp2String', function ($q, $rootScope, apiService, dbSelect, dbReplace, timeStamp2String) {

                //查询会员：传入查询条件对象（还不能模糊查询）(根据手机号码查找)
                var vip_search = function (param) {
                    param.source = '6';
                    param.brand_code = $rootScope.current_shop.BrandCode;
                    return apiService('crm/vip/search', param);
                };

                //获取最近当月生日会员列表
                var get_list_month = function (param) {
                    param.source = '6';
                    return apiService('crm/vip/get_list_by_month', param);

                };

                //获取当月生日人数 
                var get_birthday_num = function () {
                    var deferred = $q.defer();
                    var promise = deferred.promise;
                    var curBirthdayNum = 0;
                    var nowTime = new Date();
                    var nowDay = timeStamp2String(nowTime, 'month-day');
                    var nowMonth = timeStamp2String(nowTime, 'month');
                    var param = {};
                    param.fields = '*';
                    //    param.fields = 'vip_code,nickname,tel,vip_integral,consume_money,last_consume_time';
                    param.month = nowMonth;
                    param.source = '6';
                    param.shop_code = $rootScope.current_shop.ShopCode;
                    get_list_month(param).then(function (ret) {
                        
                        if (typeof ret.data.data != "undefined" && typeof ret.data.data.vip != "undefined" && typeof ret.data.data.vip.data != "undefined") {
                            if (ret.data.data.vip.data.length == 0) {
                                deferred.resolve(0);
                            } else {
                            	
                                $.each(ret.data.data.vip.data, function (i, v) {
                                    timeStamp2String(v.birthday, 'month-day')
                                    if (timeStamp2String(v.birthday, 'month-day') == nowDay) {
                                        curBirthdayNum++;
                                    }
                                });
                                deferred.resolve(curBirthdayNum);
                            }
                        } else {
                            deferred.resolve(0);
                        }
                    });
                    return promise;
                };
                //获取单个会员的详情
                var get_info = function () {

                };

                /**
                 * 获取最近消费过的会员
                 * @param {type} time 时间：3/7/15/30
                 * @returns {unresolved}
                 */
                var get_list_recent = function (param) {
                    param.source = '6';
                    return apiService('crm/vip/get_list_by_consume', param);
                };

                var get_list_point_maturity = function (ret, pageNum) {
                    var param = {
                        num: 10,
                        maturity_day: ret,
                        pageNum: pageNum
                    };
                    return apiService('crm/vip/point_maturity', param);
                };


                /**
                 * 获取会员最近的购买记录(传参数参考文档)
                 * @param {type}
                 * @param {type}
                 * @returns {undefined}
                 */
                var get_huiyuan_history = function (data) {
                    //baison_app.api.alert(({msg:data}));
                    var param = {};
                    param.fields = '*';
                    param.source = '6';
                    // param.add_time_start = '2013-11-18 17:06:51';
                    // param.add_time_end = timeStamp2String(0, 'datetime'); //'2016-3-24 17:06:51';
                    param.customer_code = data.tel;
                    param.pageNum = data.pageNum;
                    param.num = data.num;
					if (data.goods_status != undefined) {
						param.goods_status = data.goods_status;
					}
                    return apiService('crm/vip/consume_and_change_tel', param);
                };

                /**
                 * 获取某个会员推荐购买列表
                 * @param {type} vip_code 会员卡号
                 * @returns {undefined}
                 */
                var get_huiyuan_tuijian = function (vip_code) {

                };

                /**
                 * 获取某个会员积分变动记录
                 * @param {type} vip_code 会员卡号
                 * @returns {undefined}
                 */
                var get_huiyuan_change = function (vip_code,pageNum) {
                    var param = {};
                    param.fields = '*';
                    param.source = '6';
                    param.customer_code = vip_code;
                    param.pageNum = pageNum;
                    return apiService('crm/crm_vip/get_detail_by_tel', param);
                };

                /**
                 * 获取某个会员优惠券
                 * @param {type} vip_code 会员卡号
                 * @returns {undefined}
                 */
                var get_huiyuan_coupon = function (vip_code) {
                    var param = {};
                    param.source = '6';  //不需要
                    param.customer_code = vip_code;
                    //param.type = '2';
                    return apiService('crm/coupon/get_coupon_list', param);
                };

                //增加会员到服务器
                var add_huiyuan_online = function (data) {
                    var birthday = new Date(data.birthday);
                    birthday = timeStamp2String(birthday, 'date');
                    if (typeof data.UserCode == "undefined") {
                        data.daogou = $rootScope.user.UserCode;
                    } else {
                        data.daogou = data.UserCode;
                    }
                    if (typeof data.cardNo == "undefined") {
                        data.vip_code = data.tel;
                    } else {
                        data.vip_code = data.cardNo;
                    }
                    var param = {
//                        'source':6,
                        'VIP_category': data.memberCategory,
                        'customer_name': data.name,
                        'shop_code': $rootScope.current_shop.ShopCode,
                        'customer_tel': data.tel,
                        'vip_code': data.vip_code,
                        'customer_sex': data.sex,
                        'customer_code': data.tel,
                        'email': data.email,
                        'address': data.address,
                        'birthday': birthday,
                        'province': data.province,
                        'district': data.county,
                        'city': data.city,
                        'daogouyuan': data.daogou,
                        'recommender': data.rTel,
                        'skin_type': data.skin,
                        'qq': data.qq,
                        'weixin_id': data.weixin,
                        'customer_level': data.memberCategory,
                        'user_code': $rootScope.user.UserCode,
                        'source' : 6,
                        'brand_code':$rootScope.current_shop.BrandCode
                    };
                    return apiService('crm/vip/add_customer', param);
                };

                //增加会员到本地
                var add_huiyuan_local = function (data) {
                    var birthday = new Date(data.birthday);
                    birthday = timeStamp2String(birthday, 'date');
                    if (typeof data.daogou == "undefined") {
                        data.daogou = $rootScope.user.UserCode;
                    } else {
                        data.daogouyuan = data.daogou;
                    }
                    if (typeof data.cardNo == "undefined") {
                        data.vip_code = data.tel;
                    } else {
                        data.vip_code = data.cardNo;
                    }
                    var nowTime = new Date();
                    nowTime = timeStamp2String(nowTime, 'datetime');
                    var param = {
                        'VIP_category': data.memberCategory,
                        'customer_name': data.name,
                        'vip_code':data.vip_code,
                        'customer_code': data.tel,
                        'customer_tel':data.tel,
                        'customer_sex': data.sex,
                        'email': data.email,
                        'address': data.address,
                        'birthday': birthday,
                        'province': data.province,
                        'district': data.county,
                        'city': data.city,
                        'is_add_person': data.daogou,
                        'customer_integral': '0',
                        'consume_money': '0',
                        'consume_num': '0',
                        'skin_type': data.skin,
                        'qq': data.qq,
                        'weixin_id': data.weixin,
                        'is_add_time': nowTime,
                        'recommender': data.rTel,
                        'shop_code': $rootScope.current_shop.ShopCode,
                        'is_upload': '1',
                        'customer_level': data.memberCategory,
                        'user_code': $rootScope.user.UserCode
//                    customer_tel: data.tel,
//                    work_address:
//                    shop_code:
//                    password:
//                    id_card:
//                    status:
//                    nickname:
//                    type:
//                    level_time:
//                    is_online:
//                    is_offline:
//                    country:'1'
//                    marriage:
//                    education:
//                    is_edit:
//                    base_tel:
//                    base_home_tel:
                    };
                    //console.log(param);
                    return dbReplace('crm_customer', [param], ['customer_code'], ['VIP_category', 'customer_code','vip_code', 'customer_name', 'customer_level', 'customer_tel', 'customer_sex', 'email', 'address', 'birthday', 'customer_integral', 'consume_money', 'consume_num', 'province', 'city', 'skin_type', 'district', 'weixin_id', 'qq', 'is_add_person', 'is_upload', 'recommender', 'shop_code']);
                };
                var add_huiyuan = function (data) {
                    //console.log(data);
                    return add_huiyuan_online(data).then(function (success) {
                         if(success.data.status != 1) {
                             //服务器会员新增失败
                         	 baison_app.api.alert({msg: success.data.data.message});
                         	 return ;
                         }else{
                             //服务器新增成功、新增本地
                         	 return add_huiyuan_local(data);
                         }
                      
                    }).catch(function (err) {
                        var birthday = new Date(data.birthday);
                        birthday = timeStamp2String(birthday, 'date');
                        if (typeof data.daogou == "undefined") {
                            data.daogou = $rootScope.user.UserCode;
                        } else {
                            data.daogouyuan = data.daogou;
                        }
                        if (typeof data.cardNo == "undefined") {
                            data.vip_code = data.tel;
                        } else {
                            data.vip_code = data.cardNo;
                        }
                        var nowTime = new Date();
                        nowTime = timeStamp2String(nowTime, 'datetime');
                        var param = {
                            'VIP_category': data.memberCategory,
                            'customer_name': data.name,
                            'vip_code':data.vip_code,
                            'customer_code': data.tel,
                            'customer_tel':data.tel,
                            'customer_sex': data.sex,
                            'email': data.email,
                            'address': data.address,
                            'birthday': birthday,
                            'province': data.province,
                            'district': data.county,
                            'city': data.city,
                            'is_add_person': data.daogou,
                            'customer_integral': '0',
                            'consume_money': '0',
                            'consume_num': '0',
                            'skin_type': data.skin,
                            'qq': data.qq,
                            'weixin_id': data.weixin,
                            'is_add_time': nowTime,
                            'recommender': data.rTel,
                            'shop_code': $rootScope.current_shop.ShopCode,
                            'is_upload': '0',
//                    customer_tel: data.tel,
//                    work_address:
//                    shop_code:
                            'customer_level': '001'
//                    password:
//                    id_card:
//                    status:
//                    nickname:
//                    type:
//                    level_time:
//                    is_online:
//                    is_offline:
//                    country:'1'
//                    marriage:
//                    education:
//                    is_edit:
//                    base_tel:
//                    base_home_tel:
                        };
                        //console.log(param);
                        return dbReplace('crm_customer', [param], ['customer_code'], ['VIP_category', 'customer_code','vip_code', 'customer_name', 'customer_level', 'customer_tel', 'customer_sex', 'email', 'address', 'birthday', 'customer_integral', 'consume_money', 'consume_num', 'province', 'city', 'skin_type', 'district', 'weixin_id', 'qq', 'is_add_person', 'is_upload', 'recommender', 'shop_code']);

                    });
                };

                //获取本地未上传会员信息
                var get_list_local_not_upload = function () {
                    var sql = 'select * from crm_customer where is_upload="0"';
                    return dbSelect('YsPos', sql);
                };
                //获取本地会员信息根据时间
                var get_local_vip_list_by_time = function(user_code,day,start,end){
                    var sql = '';
                    if(day != ''){
                        sql = 'select count(*) as num from crm_customer where is_add_time >="' + day + '" and is_add_person="' + user_code + '"';
                    }else{
                        sql = 'select count(*) as num from crm_customer where is_add_time >="' + start + '" and is_add_time <="' + end + '"and is_add_person="' + user_code + '"';
                    }
                    //console.log(sql);
                    return dbSelect('YsPos', sql);
                };
                
                //获取会员可选择皮肤类型
                var ger_all_skin_type = function () {
                    var sql = 'select * from Pos_skin_type';
                    return dbSelect('YsPos', sql);
                };

                //新建顾客
                var add_customer = function (customer) {
                    var param = {};
                    param.tel = customer.tel;
                    param.birthday = timeStamp2String(customer.birthday, 'birthday');
                    param.sex = customer.sex;
                    param.name = customer.name;
                    param.shop_code = $rootScope.current_shop.ShopCode;
                    return apiService('crm/vip/addCustomer', param);
                };
                //获取推荐商品（本地关联商品表查找）(暂时不用)
                var get_recommend_goods = function () {
                    var sql = 'select g.* from PosAssociatedGoods p inner join PosGoods g on p.CollectionCode = g.GoodsCode';
                    return dbSelect('YsPos', sql);
                };
                //接口获取会员的消费记录,然后查出会员的购买记录
                var get_recommend_goods_by_vip_code = function(vip_code){
                    var param = {};
                    param.vip_code = vip_code;
                	return apiService('crm/vip/goods_recommend',param);
                };
                //根据推荐商品的GoodsCode获取下第一条sku
                var get_oneSku_by_goodsCode = function(GoodsCode){
                	var sql = 'select * from PosSku where GoodsCode = "'+GoodsCode+'" limit 1';
                	return dbSelect('YsPos', sql);
                };
                //获取VIP卡类别
                var get_VIP_category = function () {
                    var sql = 'select * from Pos_vip_category where is_stop =0';
                    return dbSelect('YsPos', sql);
                }
			

                return {
                    vip_search: vip_search,
                    get_list_month: get_list_month,
                    get_birthday_num: get_birthday_num,
                    get_info: get_info,
                    get_list_recent: get_list_recent,
                    get_list_point_maturity: get_list_point_maturity,
                    get_huiyuan_history: get_huiyuan_history,
                    get_huiyuan_tuijian: get_huiyuan_tuijian,
                    get_huiyuan_change: get_huiyuan_change,
                    get_huiyuan_coupon: get_huiyuan_coupon,
                    get_list_local_not_upload: get_list_local_not_upload,
                    add_huiyuan: add_huiyuan,
                    ger_all_skin_type: ger_all_skin_type,
                    add_customer: add_customer,
                    get_recommend_goods: get_recommend_goods,
                    get_VIP_category: get_VIP_category,
                    get_oneSku_by_goodsCode:get_oneSku_by_goodsCode,
                    get_recommend_goods_by_vip_code:get_recommend_goods_by_vip_code,
                    get_local_vip_list_by_time:get_local_vip_list_by_time
                };
            }
        ])


        ;
